<?php
/** * user_model Class * 
 * @package TIAP 
 * @subpackage Model 
 * @category directory user 
 * @author Ibnu Triyono 
 * @link http://twitter.com/ibnutri 
 * @note file ini masih harus dibersihkan dari fungsi2 nggak kepake
 */ 
class Directory_user_model extends MY_Model{
  var $user_table;
  var $error_message;
  function Directory_user_model(){
    parent::MY_Model();
    $this->user_table='directory_user';
    //$this->setTableName('user_tiab');
    $this->setTableName('directory_user');
    $this->load->library('session');
    $this->load->helper('date');
    $this->load->helper('ip');
    $this->user_location_table='user_location';
    $this->user_info_table='user_info';
    $this->user_household_table='user_household';
    $this->user_network_table='user_network';
    $this->user_political_bias_table='user_political_bias';
    $this->user_settings_table='user_settings';
    $this->user_setting_network_alert_table='user_setting_network_alert';
  }
  /** * method hash_password *
   * 
   * @description hash inputted text into hashed string, algorithm md5 (temporary) 
   * @paramater password string
   * @return string 
   */
  function hash_password($password = ''){
    $return_password = md5($password);
    return $return_password;
  }
  /** * method send_activation_email *
   * 
   * @description send activation email for signup 
   * @paramater email string
   *		activation_link string
   * @return boolean 
   */
  /**
  *    get_user_tiab method
  *
  *    @description Get the selected value from table user_tiab
  *    @param     string $id
  *    @result row array
  */
  
  function get_detail($id){
    $query = $this->db->get_where($this->user_table, array('id' => $id));             
    return $query->row_array();
  }
  
  /**
  *    get_list_user_tiab method
  *
  *    @description Get all value from table user_tiab
  *    @result result array
  */
  
  function get_list_user_tiab(){
    //$query = $this->db->get_where($this->user_table, array('id' => $id));             
    $query = $this->db->get($this->user_table);
    return $query->result_array();
  }

  function get_user_by_success_code($success_string = ''){
    $query = $this->db->get_where($this->user_table, array('success_page_code' => $success_string));             
    return $query->row_array();
  }
  function get_user_by_email($email = ''){
    $query = $this->db->get_where($this->user_table, array('email' => $email));             
    return $query->row_array();
  }
  /*
   * method find_user
   * @description finding user by username or email, only return 1 row/or false if failed
   * @paramater $keyword string username or email
   */
  function find_user($keyword = ''){
    if($keyword == ''){
      return FALSE;
    }
    $this->db->or_where('email',$keyword);
    $query = $this->db->get($this->user_table);
    if($query->num_rows() > 0){
      return $query->row_array();
    }else{
      return FALSE;
    }
  }
  /*
   * method create_reset_password_code
   * @description creating code to use as token on reseting password (yes it will expired overtime)
   *
   *
   */
  function create_reset_password_code($email='',$username = ''){
    $kacang = 'kacang ijo';
    $hash_string = md5(date('Y-m-d H:i:s').$email.$username.$kacang);
    $expire_date = date('U') + 3600;
    $code = $hash_string.'-'.$expire_date.'-user';
    return $code;
  }
  /*
   * method set_reset_password_code
   * @description creating code to use as token on reseting password (yes it will expired overtime)
   *
   *
   */
  function set_reset_password_code($user_tiab_id='',$reset_password_code = ''){
    $array_user_password_code = array(
	    'reset_password_code'=>$reset_password_code
    );
    $this->db->where('id',$user_tiab_id);
    $this->db->update($this->user_table,$array_user_password_code);
    return TRUE;
  }
  /** * method send_forgot_password_email *
   * 
   * @description send activation email for signup 
   * @paramater email string
   *		activation_link string
   * @return boolean 
   */
  function send_forgot_password_email($email,  $username,$reset_password_code){
    $username = str_replace('@','[at]',$username);
    $config = array(
      'mailtype'=>'html'
    );
    $reset_password_link = site_url("directory/reset_password/{$username}/$reset_password_code");
    $data = array(
      'username'=>$email,
      'reset_password_link'=>$reset_password_link 
    );
    $email_content = $this->load->view(TEMPLATE_NAME.'/front/mail/forgot_password_request',$data, true);
    $this->load->library('email');
    $this->email->initialize($config);
    
    $this->email->from('noreply@mykprisguide.com', NOREPLY_ADD);
    
    $this->email->to($email);
    
    $this->email->subject(NOREPLY_ADD.' - directory password reset e-mail');
    $this->email->message($email_content);
    if($this->email->send()){
      return TRUE;
    }else{
      return FALSE;
    }
  }
  /**
  * function forgot_password_email
  * send email to user, with content their email and password
  * 
  * @param mixed $email
  * @param mixed $password
  */
  function forgot_password_email($email, $password){    
    $config = array(
      'mailtype'=>'html'
    );    
    $data = array(
      'username'=>$email,
      'password'=>$password 
    );
    $email_content = $this->load->view(TEMPLATE_NAME.'/front/mail/forgot_password',$data, true);
    $this->load->library('email');
    $this->email->initialize($config);    
    $this->email->from('noreply@mykprisguide.com', NOREPLY_ADD);
    $this->email->to($email);
    $this->email->subject('Design directory password reminder');
    $this->email->message($email_content);
    if($this->email->send()){
      return TRUE;
    }else{
      return FALSE;
    }
  }
  
  function check_reset_code($username ='',$codes = array()){
    $hash = $codes[0];
    $expire_date = $codes[1];
    $bonus = $codes[2];
    if($expire_date < date('U')){
      return FALSE;
    }
    $this->db->where('id',$username);
    $this->db->where('reset_password_code',$hash.'-'.$expire_date.'-user');
    $query = $this->db->get($this->user_table);
    if($query->num_rows() > 0){
      return TRUE;
    }else{
      return FALSE;
    }

  }

  function resend_activation_email($activation_code = ''){
    $user_detail = $this->get_user_by_activation_code($activation_code);
    $activation_link = site_url('directory/activate/'.md5($user_detail['email']).'/'.$user_detail['activation_code']);
    $this->send_activation_email($user_detail['email'],$user_detail['first_name'],$activation_link);
    return TRUE;
  }
  function get_user_by_activation_code($activation_code = ''){
    $query = $this->db->get_where($this->user_table, array('activation_id' => $activation_code));             
    return $query->row_array();
  }
  function send_activation_email($email,$name,$activation_link){
    $config = array(
      'mailtype'=>'html'
    );
    $data = array(
      'name'=>$name, 
      'email'=>$name, 
      'activation_link'=>$activation_link, 
    );
    $email_content = $this->load->view(TEMPLATE_NAME.'/front/mail/directory_activation_email',$data, true);
    $this->load->library('email');
    $this->email->initialize($config);
    
    $this->email->from('noreply@mykprisguide.com', NOREPLY_ADD);
    $this->email->to($email);
    //$this->email->cc('another@another-example.com');
    //$this->email->bcc('them@their-example.com');
    $this->email->subject(NOREPLY_ADD.' - Directory activation email ');
    $this->email->message($email_content);
    if($this->email->send()){
      return TRUE;
    }else{
      return FALSE;
    }
  }
  /* method reset_password
   * @description reset_password for user
   * 
   */
  function reset_password($username, $password){
    $array_reset_password = array(
	    'password'=>$this->hash_password($password),
	    'password_real'=>mask_password($password),
	    'reset_password_code'=>''
	    );
    $this->db->where('id',$username);
    $this->db->update($this->user_table,$array_reset_password);
  }
  
  /**
  * update_user_tiab method
  *
  * @description Update data to table user_tiab 
  *              if no uploaded file and empty real_pass, no update to avatar field and real_pass field
  *              and if empty avatar and not empty real_pass, no update to avatar field
  *              else update table with all parameter
  * @param      string $username
  *             string $firstname
  *             string $surname
  *             string $email
  *             string $real_pass
  *             string $password
  *             string $avatar                              
  *             string $user_tiab_id
  * @result query
  */
     
   /** * method find_user *
   * 
   * @description find user_tiab search by username 
   * @paramater username string
   * @return row 
   * this function deprecated
   */
  /*
   function find_user($username = ''){
       //$query = $this->db->get_where($this->user_table, array('username' => $username));             
       //return $query->row_array();
       $this->db->select('id,username');
       $this->db->from($this->user_table);
       $this->db->like('username' ,$username);
       $query = $this->db->get();
       return $query->result_array();
       //return $this->db->last_query();
   }
   */
  /**
   *
   * @return boolean
   * @access public
   */
  function check_not_remembered_login()
  {
    if ($this->session->userdata('directory_user_id') AND $this->session->userdata('directory_not_from_rememberme') == 'yes')
    {
      return TRUE;
    }
    return FALSE;
  }
  
  function member_login($username='', $password='')
  {
        $username = trim($username);
        $password = trim($password);
        
        if ($username != '' AND $password != '')
            {
                  $condition = " (email ='{$username}') ";   
                  //$user_data = $this->getDetail('',$condition);
                  //$this->db->where($condition);
                  $this->db->where('email',$username);
                  //$this->db->or_where('email',$username);
            
                  $query = $this->db->get($this->user_table);
                  if ($query->num_rows() > 0)
                  {
                	  $user_data = $query->row_array();
                          if ($user_data['password'] != $password)
                          {
                                $this->set_error('sorry wrong password.');
                                return false;
                           }
                           elseif($user_data['activation_status'] != '1')
                           {
                                $this->set_error('please activate your account.');
                                return false;
                           }
                  	       else
                           {
                                $this->set_user_session($user_data['id'], $user_data['username']
                                                  , 'yes', 'yes'
                                                  , $user_data['firstname']?$user_data['firstname']:$user_data['username']
                                                  , mysql_to_unix($user_data['lastlogin'])
                                                  );
                                $data['lastlogin'] = date('Y-m-d H:i:s');
                    	        $this->db->where('id',$user_data['id']);
                    	        $this->db->update($this->user_table,$data);
                    	        return $user_data;
                        }
                  }
                  else{
                    $this->set_error('that e-mail does not exist in the database.');
                  }
        }
        else
        {
            $this->set_error('Please fill in email and password!');
        }
        //echo $this->error_message;
        return FALSE;
  }
  /**
   *  method login
   * @param $username string
   * @param $password string
   * @return user_data or FALSE
   */
  function login($username='', $password='', $facebook_user_id=0, $openid_url=''){
    
    $username = trim($username);
    $password = trim($password);
    $facebook_user_id = intval($facebook_user_id);
    $openid_url = trim($openid_url);
    if ($username != '' AND $password != ''){
      $condition = " (username='{$username}' OR email ='{$username}') ";   
      //$user_data = $this->getDetail('',$condition);
      //$this->db->where($condition);
      $this->db->where('email',$username);
      //$this->db->or_where('email',$username);

      $query = $this->db->get($this->user_table);
      if ($query->num_rows() > 0){
	  $user_data = $query->row_array();
          if ($user_data['password'] != $password){
            $this->set_error('sorry wrong password.');
            return false;
        }elseif($user_data['activation_status'] != '1'){
            $this->set_error('Please activate your account.');
            return false;
        }
	else{
            $this->set_user_session($user_data['id'], $user_data['username']
                                  , 'yes', 'yes'
                                  , $user_data['firstname']?$user_data['firstname']:$user_data['username']
                                  , mysql_to_unix($user_data['lastlogin'])
                                  );
            $data['lastlogin'] = date('Y-m-d H:i:s');
	        $this->db->where('id',$user_data['id']);
	        $this->db->update($this->user_table,$data);
	        return $user_data;
        }
      }
      else{
        $this->set_error('that e-mail does not exist in the database.');
      }
    }
    else
    {
      $this->set_error('Please fill in username and password!');
    }
    //echo $this->error_message;
    return FALSE;
  }
  /**
   *  method force_login
   *  @description forcing login using username only, use wisely (currently only used on activation user)
   * @param $username string
   * @return user_data or FALSE
   */
  function force_login($username ='')
  {
    $username = trim($username);
    if ($username != '' )
    {
      //$username = $this->adodb->qstr($username, get_magic_quotes_gpc());
      //$password = $this->adodb->qstr($password, get_magic_quotes_gpc());
      //$username = $this->db->escape($username);
      //$password = $this->db->escape($password);
      $condition = " username=$username AND  activation_status='active'  ";
      $where_data = array(
	      'username'=>$username,
	      'activation_status'=>'active',
	      );
      $result = $this->db->get_where($this->user_table,$where_data,1);
      //echo $this->db->last_query();
      if ($result AND $result->num_rows() == 1)
      {
        //set session
        $user_data = $result->row_array();
        $this->set_user_session($user_data['id'], $user_data['username']
                              , 'yes', 'yes'
                              , $user_data['firstname']?$user_data['firstname']:$user_data['username']
                              , mysql_to_unix($user_data['last_login'])
                              );
        //save current login info
        $data['last_login'] = date('Y-m-d H:i:s');
        $data['last_login_ip'] = encode_ip($this->input->ip_address());
	$this->db->where('id',$user_data['id']);
	$this->db->update($this->user_table,$data);
	return TRUE;
      }
      else
      {
	return FALSE;
      }
    }
    else
    {
      return FALSE;
    }
    return FALSE;
  }
  /**
   *
   * @param $user_id integer
   * @param $username string
   * @param $user_type string
   * @param $logged_in string
   * @param $not_from_rememberme string
   * @return void
   */
  function set_user_session($directory_user_id, $directory_username, $directory_logged_in, $directory_not_from_rememberme
                          , $directory_full_name=''
                          , $directory_last_login=0
                          )
  {
    if ($last_login == 0) $last_login = time();
    $session = compact('directory_user_id', 'directory_username',  'directory_logged_in', 'directory_not_from_rememberme', 'directory_full_name',  'directory_last_login');
    $session['directory_latest_rows'] = array();
    $this->session->set_userdata($session);
  }
  /**
   *
   * @return void
   */
  function unset_user_session()
  {
    $session['directory_user_id']   = '';
    $session['directory_username']  = '';
    $session['directory_user_type'] = '';
    $session['directory_logged_in'] = '';
    $session['directory_not_from_rememberme'] = '';
    $session['directory_full_name'] = '';
    $session['directory_facebook_user_id'] = '';
    $session['directory_last_login'] = '';
    $session['directory_latest_rows'] = '';
    $session['directory_status'] = '';
    $session['directory_facebook_user'] = '';
    $this->session->unset_userdata($session);
  }
  /**
   * @description check whether user logged in or not, TRUE means logged in 
   * @return boolean
   * @access public
   */
  function check_login(){
    
    if ($this->check_not_remembered_login())
    {
      return TRUE;
    }
    
    //check rememberme cookies
    $CI =& get_instance();
    $CI->load->model('rememberme_cookies_model');
    $cookie_data = $CI->rememberme_cookies_model->read_cookies();
    
    if ($cookie_data AND is_array($cookie_data))
    {
        
      $result = $CI->rememberme_cookies_model->check($cookie_data['directory_user_id']);
      
      
      if ($result)
      {
        //get user_data
        $user_data = $this->get_detail($cookie_data['directory_user_id']);
        if ($user_data AND $user_data['status']!='suspended' AND $user_data['status']!='deleted')
        {
          //set session
          $this->set_user_session($user_data['id'], $user_data['username']
                                , $user_data['user_type'], 'yes', 'no'
                                , $user_data['full_name']?$user_data['full_name']:$user_data['username']
                                , 0
                                , mysql_to_unix($user_data['last_login'])
                                , $user_data['status']);
          return TRUE;
        }
      }
    }
    
    return FALSE;
    }

	
	/**
    * method static_page
    * upload image and select descriptions in staticpage(about,team,donation,term condition,privacy)    
    * path images to upload : .static/uploads/
    * revision: sohould be better coded
    */
    function delete_user($user_tiab_id = ''){
      if($user_tiab_id != ''){
	$this->db->where('user_tiab_id',$user_tiab_id);
	$this->db->delete($this->user_household_table);
	$this->db->where('user_tiab_id',$user_tiab_id);
	$this->db->delete($this->user_info_table);
	$this->db->where('user_tiab_id',$user_tiab_id);
	$this->db->delete($this->user_location_table);
	$this->db->where('id_user',$user_tiab_id);
	$this->db->delete($this->user_network_table);
	$this->db->where('user_tiab_id',$user_tiab_id);
	$this->db->delete($this->user_political_bias_table);
	$this->db->where('user_tiab_id',$user_tiab_id);
	$this->db->delete($this->user_settings_table);
	$this->db->where('user_tiab_id',$user_tiab_id);
	$this->db->delete($this->user_setting_network_alert_table);
	$this->db->where('id',$user_tiab_id);
	$this->db->delete($this->user_table);
	return TRUE;
      }else{
	return FALSE;
      }
    }
    function set_error($message){
      $this->error_message = "$message";
    }

  /**
   * method check_available_email
   * @description checek wether the email available / email exist. mainly used in registration
   * input email string
   * output Boolean TRUE if email doesn't exist/available for registration
   *
   */
  function check_available_email($email,$user_id = ""){
    $this->db->where("email",$email);
    if($user_id != ""){
      $this->db->where("id !=",$user_id);
    }
    $query = $this->db->get($this->user_table);
        if ($query->num_rows() > 0) {
	    return FALSE;
        } else {
            return TRUE;
        }
  }
  function update_login_info($user_id, $email, $password = ""){
      if($password == ""){
	$array_update = array(
		'email'=>$email
		);
      }else{
	$array_update = array(
		'email'=>$email,
		'password'=>md5($password),
		'password_real'=>$password,
		);
      }
      $this->db->where('id',$user_id);
      $this->db->update($this->user_table, $array_update);
      
  }
  
	function update_email($email = '', $directory_user_id = 0){
	    $data = array('email'=>$email);
	    $this->db->where('id', $directory_user_id);
	    $this->db->update($this->user_table, $data);    
  	}	 
}
	
/* End of file directory_user_model.php */ 
/* Location: ./system/application/models/directory_user_model.php */